package address

import (
	"gitee.com/xuxinzhi2206/corehub/database/mysql"
	"gorm.io/gorm"
)

type Address struct {
	gorm.Model
	UserID          int64  `json:"userid" gorm:"column:userid;type:int(11);comment:用户ID"`
	ConsigneeName   string `json:"consignee_name" gorm:"column:consignee;type:varchar(40);comment:收件人姓名"`
	Mobile          string `json:"mobile" gorm:"column:mobile;type:varchar(11);comment:电话号"`
	Area            string `json:"area" gorm:"column:area;type:varchar(100);comment:地区"`
	DetailedAddress string `json:"detailed_address" gorm:"column:detailed_address;type:varchar(100);comment:详细地址"`
	Tag             int64  `json:"tag" gorm:"column:tag;type:int(11);comment:地址标签,例如家,公司,学校,父母,朋友,自定义"`
	DefaultAddress  bool   `json:"default_address" gorm:"column:default_address;type:tinyint(1);default:false;comment:是否为默认地址, 0为默认地址, 1为非默认地址"`
}

func (a *Address) CreateAddress() (*Address, error) {
	return a, mysql.WithMysql(func(db *gorm.DB) error {
		return db.Create(a).Error
	})
}

func (a *Address) UpdateAddress(id int64) (*Address, error) {
	return a, mysql.WithMysql(func(db *gorm.DB) error {
		return db.Model(a).Where("userid = ?", id).Updates(a).Error
	})
}

func (a *Address) DeleteAddress() error {
	return mysql.WithMysql(func(db *gorm.DB) error {
		return db.Model(a).Where("userid = ?", a.UserID).Delete(a).Error
	})
}

func SearchAddress(limit, offset int) ([]*Address, int64, error) {
	var detail []*Address
	var total int64

	err := mysql.WithMysql(func(db *gorm.DB) error {
		off := (offset - 1) * limit
		if err := db.Offset(off).Limit(limit).Find(&detail).Error; err != nil {
			return err
		}

		if err := db.Model(&detail).Count(&total).Error; err != nil {
			return err
		}
		return nil
	})
	return detail, total, err
}
